package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.bean.OrderDetail;
import com.itheima.bean.Orders;
import com.itheima.common.BaseContext;
import com.itheima.common.PageBean;
import com.itheima.common.R;
import com.itheima.dto.OrdersDto;
import com.itheima.exception.CustomException;
import com.itheima.service.OrderDetailService;
import com.itheima.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


import java.util.Collections;
import java.util.LinkedList;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RequestMapping("/order")
@RestController
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderDetailService orderDetailService;

    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders order) {
        //1.调用service完成业务处理
        orderService.submit(order);

        //2.返回下单成功
        return R.success("下单成功！");
    }

    @GetMapping("/page")
    public R<PageBean> selectPage(Integer page, Integer pageSize, String number, String beginTime, String endTime) {
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotEmpty(number),Orders::getNumber,number);
        wrapper.ge(StringUtils.isNotEmpty(beginTime),Orders::getOrderTime,beginTime);
        wrapper.le(StringUtils.isNotEmpty(endTime),Orders::getOrderTime,endTime);
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        orderService.page(ordersPage,wrapper);
        List<Orders> records = ordersPage.getRecords();
        long total = ordersPage.getTotal();
        return R.success(new PageBean(records,total));
    }


    @GetMapping("/userPage")
    public R<PageBean> lastOrder(int page, int pageSize) {
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Orders::getUserId, userId);
        if (pageSize == 1) {//如果pageSize是1，说明前端想查询该用户最新的那条订单
            List<Orders> list = orderService.list(lqw);
            Orders lastOrder = list.get(list.size() - 1);
            LambdaQueryWrapper<OrderDetail> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(OrderDetail::getOrderId, lastOrder.getId());
            List<OrderDetail> orderDetails = orderDetailService.list(wrapper);
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(lastOrder, ordersDto);
            ordersDto.setOrderDetails(orderDetails);
            LinkedList<OrdersDto> ordersDtos = new LinkedList<>();
            ordersDtos.add(ordersDto);
            return R.success(new PageBean(ordersDtos, 1));
        }
        //以下是分页查询
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        orderService.page(ordersPage, lqw);
        List<Orders> orders = ordersPage.getRecords();
        if (orders == null || orders.size() == 0) throw new CustomException("您还未下单");
        List<OrdersDto> collect = orders.stream().map(order -> {
            LambdaQueryWrapper<OrderDetail> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(OrderDetail::getOrderId, order.getId());
            List<OrderDetail> orderDetails = orderDetailService.list(wrapper);
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(order, ordersDto);
            ordersDto.setOrderDetails(orderDetails);
            return ordersDto;
        }).collect(Collectors.toList());
        //开始计算最后一页页码
        long total = ordersPage.getTotal();
        Long pages = total / pageSize;
        if (total % pageSize != 0) pages++;
        PageBean<OrdersDto> pageBean = new PageBean<>(collect, total);
        pageBean.setPages(pages);//返回最后一页的页码给前端，前端需要这样一个数据。
        return R.success(pageBean);
    }
    @PutMapping
    public R<String> update(@RequestBody Orders orders){
        orderService.updateById(orders);
        return R.success("开始派送");
    }

}
